/**
 * create by young (young2f@outlook.com) on 2020/9/19
 */
'use strict';
import React from 'react';
import {Form, Icon, Modal, Upload} from 'antd';
import notify from "../NotificationExtra";
import ViewTitle from "../ViewTitle";
import FormBase from "../Base/FormBase";

@Form.create()

export default class UploadPic extends FormBase {
  constructor(props) {
    super(props);
    const {fileList} = this.props;
    this.state = {fileList};
  }


  picHandlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj);
      console.log(file.preview);
    }
    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true
    });
  };
  picHandleChange = ({fileList}) => {
    const {callback} = this.props;
    let isLt2M = 0;
    _.map(fileList, async file => {
      isLt2M += file.size / 1024 / 1024;
      if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj);
        //file.thumbUrl = file.response ? file.response.data : fileList.file.thumbUrl;
      }
    });
    console.log('isLt2MisLt2M', isLt2M);
    if (isLt2M > 0.5) {
      notify({type: 'error', message: '图片文件过大或数量过多！'});
    }
    const temp = this.state;
    temp.fileList = fileList;
   callback&& callback({fileList});

    this.setState({...temp});
  };

  render() {
    const {title} = this.props;

    const {fileList, previewVisible, previewImage} = this.state;

    return (
      <div style={{marginLeft: '64px'}}>
        {title && <ViewTitle
          title={title}
        ></ViewTitle>}
        <Upload
          action={'http://127.0.0.1:18008/api/global/upload?type=inboundLot'} // 没有用，直接存图片流文件
          listType="picture-card"
          fileList={fileList}
          accept={".png,.jpg"}
          onPreview={this.picHandlePreview}
          onChange={this.picHandleChange}
          onDownload={file => {
            console.log('ondownlad', file);
          }}
          beforeUpload={(file, fileList) => {
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
              notify({type: 'error', message: '文件过大！'});
              return isLt2M;
            }
            return false;
          }}
        >
          {<div>
            <Icon type="plus"/>
            <div className="ant-upload-text">上传图片</div>
          </div>}
        </Upload>
        <Modal visible={previewVisible} footer={null} onCancel={() => {
          this.setState({previewVisible: false});
        }}>
          <img alt="example" style={{width: '100%'}} src={previewImage}/>
        </Modal>
      </div>
    );
  }
}


